package com.shengwei.truck.driver.model;

import android.app.Application;
import android.content.ContentValues;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.shengwei.truck.driver.bean.JsonCar;
import com.shengwei.truck.driver.bean.JsonCurUserInfoData;
import com.shengwei.truck.driver.bean.JsonDataCommon;
import com.shengwei.truck.driver.bean.JsonLoginData;
import com.shengwei.truck.driver.bean.JsonMsgListData;
import com.shengwei.truck.driver.bean.JsonPostFileData;
import com.shengwei.truck.driver.bean.JsonPoundsState;
import com.shengwei.truck.driver.bean.JsonStatisticsOneDayData;
import com.shengwei.truck.driver.bean.JsonStatisticsYmdData;
import com.shengwei.truck.driver.bean.JsonTrackData;
import com.shengwei.truck.driver.bean.LocationPack;
import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.PoundsListBean;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.bean.task.JsonOrderDetailData;
import com.shengwei.truck.driver.bean.task.JsonOrderListData;
import com.shengwei.truck.driver.bean.task.JsonSearchUserData;
import com.shengwei.truck.driver.bean.task.JsonTaskDetailData;
import com.shengwei.truck.driver.bean.task.JsonTaskListData;
import com.shengwei.truck.driver.bean.task.OrderItem;
import com.shengwei.truck.driver.bean.task.TaskItem;
import com.shengwei.truck.driver.net.RetrofitManager;
import com.shengwei.truck.driver.utils.MyLogCat;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;
/**
 * 访问登录页面相关的接口
 */
public class DataSource extends BaseDataSource  {
    static DataSource instance;
    String TAG = "DataSource";

    /**
     * 获取DataSource单例
     * @return
     */
     static synchronized public DataSource  getSingleInstance() {
        if(instance == null) {
            synchronized (DataSource.class) {
                instance = new DataSource();
            }
        }
        return instance;
    }
    /**
     * 登录服务器接口
     * @param username： 账号
     * @param password： 密码
     * @param liveData: 要修改的LiveData数据，同时View层（LoginActivity）监听LiveData的数据变更，从而更新UI
     * @return
     */
    public MutableLiveData<Result<JsonLoginData>> login(String username, String password, MutableLiveData<Result<JsonLoginData>> liveData, Application app) {
        try {
            JSONObject jsonUser = new JSONObject();
            jsonUser.put("username",username);
            jsonUser.put("password",password);
            jsonUser.put("appId", MyConstant.APP_ID);
            String jsonParam = jsonUser.toString();
            RequestBody userBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .login(userBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            liveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonLoginData> jsonModel) -> {
                        liveData.postValue(Result.response(jsonModel));
                        JsonLoginData jsonLoginData = jsonModel.getData();
                        String token = jsonLoginData.getToken();
                        String tokenHead = jsonLoginData.getTokenHead();
                        //保存用户数据在本地SharePreference
                        saveUserData(token,tokenHead,app);

                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,liveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            liveData.postValue(Result.error(throwable));
                        }
                    });
            return liveData;

        } catch (Exception e) {
            liveData.postValue(Result.error(e.getCause()));
        }
        return liveData;
    }

    /**
     * 保存登录返回的token等 用户信息
     * @param token: 服务器登录接口返回的token
     * @param tokenHead 服务器登录接口返回的tokenHead,联合token一起作为header就可以调用登录以外的其它接口了
     * @param app: 全局context
     */
    public void saveUserData(String token,String tokenHead,Application app) {
        User user = User.getInstance(app);
        ContentValues value = new ContentValues();
        value.put("token",token);
        value.put("tokenHead",tokenHead);
        user.saveUserInfo(value);
    }

    /**
     * 获取短信验证码
     * @param mobileNum： 手机号
     * @param pageType： 页面类型: 注册页面，忘记密码页面，修改密码页面
     * @param liveData： 要修改的LiveData数据，同时View层（如RegistActivity）监听LiveData的数据变更，从而更新UI
     * @return
     */
    public MutableLiveData<Result<String>> getSmsCode(String mobileNum,String pageType, MutableLiveData<Result<String>> liveData) {
        try {
            JSONObject jsonUser = new JSONObject();
            jsonUser.put("phone",mobileNum);
            jsonUser.put("type",pageType);
            jsonUser.put("appId",MyConstant.APP_ID);
            String jsonParam = jsonUser.toString();
            RequestBody smsBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .getSmsCode(smsBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            liveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        liveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,liveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            liveData.postValue(Result.error(throwable));
                        }
                    });
            return liveData;

        } catch (Exception e) {
            liveData.postValue(Result.error(e.getCause()));
        }
        return liveData;
    }

    /**
     * 去注册
     * @param registParamMap: 注册时需要的请求参数
     * @param liveData: 修改的LiveData数据，同时View层（如RegistActivity）监听LiveData的数据变更，从而更新UI
     * @return 服务器返回的数据，以liveData形式返回，供View层监听
     */
    public MutableLiveData<Result<String>> regist(HashMap<String,String>registParamMap, MutableLiveData<Result<String>> liveData) {
        try {
            JSONObject registParamJson = new JSONObject(registParamMap);
            RequestBody registBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),registParamJson.toString());
            mSubscription = RetrofitManager.getApiService()
                    .regist(registBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            liveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        liveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,liveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            liveData.postValue(Result.error(throwable));
                        }
                    });
            return liveData;

        } catch (Exception e) {
            liveData.postValue(Result.error(e.getCause()));
        }
        return liveData;
    }


    /**
     * 获取任务列表
     * @param taskStatus :  任务单状态
     * @param pageNum ：    页码
     * @param pageSize ：  一页中的条目数
     * @param isForward: 是否转派列表
     * @param taskListLiveData ： 以liveData形式返回，供View层监听
     * @return
     */
   public MutableLiveData<Result<JsonTaskListData>> getTaskList(String taskStatus, int pageNum, int pageSize,int isForward, MutableLiveData<Result<JsonTaskListData>> taskListLiveData)
   {
       try {
           mSubscription = RetrofitManager.getApiService()
                   .getTaskList(taskStatus,pageNum,pageSize,isForward)
                   .subscribeOn(Schedulers.io())
                   .observeOn(AndroidSchedulers.mainThread())
                   .doOnSubscribe(new Action0() {
                       @Override
                       public void call() {
                          //gxw-taskListLiveData.postValue(Result.loading(""));
                       }
                   })

                   //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                   .subscribe((JsonDataCommon<JsonTaskListData> jsonModel) -> {
                       taskListLiveData.postValue(Result.response(jsonModel));
                   }, (Throwable throwable) -> {
                       //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                       if (throwable instanceof HttpException) {
                           String exceptionMsg = dealExceptionContent(throwable,taskListLiveData);
                           MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                       }
                       else {
                           taskListLiveData.postValue(Result.error(throwable));
                       }
                   });
           return taskListLiveData;

       } catch (Exception e) {
           taskListLiveData.postValue(Result.error(e.getCause()));
       }

       return taskListLiveData;
   }

    /**
     * 修改密码与忘记密码页面公用
     * @param mobileNum： 手机号
     * @param password： 新密码
     * @param captcha： 验证码
     * @param modifyPwdLiveData：服务器返回的数据填充到livedata里
     * @param pageType:页面类型
     */
    public void resetPwd(String mobileNum, String password, String captcha, String pageType,MutableLiveData<Result<String>> modifyPwdLiveData) {

        try {
            JSONObject jsonUser = new JSONObject();
            jsonUser.put("phone",mobileNum);
            jsonUser.put("password",password);
            jsonUser.put("captcha",captcha);
            jsonUser.put("type",pageType);
            if(pageType.equals("FORGET_PASSWORD")) {
                jsonUser.put("appId",MyConstant.APP_ID);
            }
            String jsonParam = jsonUser.toString();
            RequestBody resetPwd = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .resetPwd(resetPwd)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            modifyPwdLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        modifyPwdLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,modifyPwdLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            modifyPwdLiveData.postValue(Result.error(throwable));
                        }
                    });

        } catch (Exception e) {
            modifyPwdLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 获取任务详情
     * @param taskId： 任务id
     * @param taskDetailLiveData： 服务器返回的数据填充到livedata里
     */
    public void getTaskDetail(String taskId, MutableLiveData<Result<JsonTaskDetailData>> taskDetailLiveData) {
        try {
            if(taskId ==null) {
                return;
            }
            mSubscription = RetrofitManager.getApiService()
                    .getTaskDetail(taskId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            taskDetailLiveData.postValue(Result.loading(""));
                        }
                    })
                    .doOnCompleted(new Action0() {
                        @Override
                        public void call() {
                            MyLogCat.i(TAG,"doOnCompleted");
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonTaskDetailData> jsonModel) -> {
                        taskDetailLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,taskDetailLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            taskDetailLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            taskDetailLiveData.postValue(Result.error(e.getCause()));
        }
    }


    /**
     * 获取当前用户信息
     * @param curUserInfoLiveData 服务器返回的数据填充到livedata里
     */
    public void getUserInfo(MutableLiveData<Result<JsonCurUserInfoData>> curUserInfoLiveData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .getCurUserInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                           //gxw-为了界面友好，这里取消进度框 curUserInfoLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonCurUserInfoData> jsonModel) -> {
                        curUserInfoLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,curUserInfoLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            curUserInfoLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            curUserInfoLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 修改手机号
     * @param identify
     * @param mobileNum ：新手机号
     * @param captcha ：短信验证码
     * @param modifyMobileData 服务器返回的数据填充到livedata里
     */
    public void updateMobile(String identify, String mobileNum, String captcha, MutableLiveData<Result<String>> modifyMobileData) {

        try {
            JSONObject jsonUser = new JSONObject();
            jsonUser.put("phone",mobileNum);
            jsonUser.put("captcha",captcha);
            jsonUser.put("idCard",identify);
            String jsonParam = jsonUser.toString();
            RequestBody modifyMobile = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);
            mSubscription = RetrofitManager.getApiService()
                    .updateMobile(modifyMobile)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            modifyMobileData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        modifyMobileData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,modifyMobileData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            modifyMobileData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            modifyMobileData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 上传文件
     * @param file： 待上传的文件
     * @param postFileLiveData  服务器返回的数据填充到livedata里
     */
    public void postPicture(File file, boolean isThumb,MutableLiveData<Result<JsonPostFileData>> postFileLiveData) {
        try {
             //RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); //OK
             RequestBody requestFile = RequestBody.create(MediaType.parse(""), file); //OK
             MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);//OK
             mSubscription = RetrofitManager.getApiService()
                    .postFile(filePart,isThumb)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            postFileLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonPostFileData> jsonModel) -> {
                        postFileLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,postFileLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            postFileLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            postFileLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 调用业务服务器的上传头像接口
     * @param idCard
     * @param name
     * @param avatarThumbUrl : 头像缩略图地址
     * @param avatarUrl ： 头像原图地址
     * @param updtUserInfoLiveData ： 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void updateUserInfo(String idCard, String name, String avatarThumbUrl, String avatarUrl, String smsCode,MutableLiveData<Result<String>> updtUserInfoLiveData) {
        try {
            JSONObject jsonUpdateUserInfo = new JSONObject();
            jsonUpdateUserInfo.put("avatarThumbUrl",avatarThumbUrl);
            jsonUpdateUserInfo.put("avatarUrl",avatarUrl);
            jsonUpdateUserInfo.put("realName",name);
            jsonUpdateUserInfo.put("idCard",idCard);
            jsonUpdateUserInfo.put("captcha",smsCode);
            String jsonParam = jsonUpdateUserInfo.toString();
            RequestBody updateUseInforBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .updateUserInfo(updateUseInforBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            updtUserInfoLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        updtUserInfoLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,updtUserInfoLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            updtUserInfoLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            updtUserInfoLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 接受任务
     * @param taskId  任务ID
     * @param taskStatus: 传 1 表示要接受任务
     * @param recvTaskLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void recvTaskDetail(String taskId, int taskStatus, MutableLiveData<Result<String>> recvTaskLiveData) {
        try {
            JSONObject recvTaskParams = new JSONObject();
            recvTaskParams.put("id",taskId);
            recvTaskParams.put("taskStatus",taskStatus);
            String jsonParam = recvTaskParams.toString();
            RequestBody recvTaskBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .recvTask(recvTaskBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            recvTaskLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        recvTaskLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,recvTaskLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            recvTaskLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            recvTaskLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 模糊查询车辆名称
     * @param keyWord
     * @param searchLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void searchCarName(String keyWord, MutableLiveData<Result<ArrayList<JsonCar>>> searchLiveData) {
        try {

            mSubscription = RetrofitManager.getApiService()
                    .searchCarName(keyWord)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            searchLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<ArrayList<JsonCar>> jsonModel) -> {
                        searchLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,searchLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            searchLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            searchLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 根据车辆ID,获取车辆详情
     * @param JsonCarId
     * @param JsonCarDetailLiveData
     */
    public void getCarDetail(String JsonCarId, MutableLiveData<Result<JsonCar>> JsonCarDetailLiveData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .getCarDetail(JsonCarId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            JsonCarDetailLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonCar> jsonModel) -> {
                        JsonCarDetailLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,JsonCarDetailLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            JsonCarDetailLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            JsonCarDetailLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 绑定车辆信息
     * @param JsonCarNum： 车牌号
     * @param JsonCarId： 车辆名称ID
     * @param isEtcNum: etc号,1有，0无
     * @param durableYears: 使用年限
     * @param bindJsonCarLiveData: 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void bindCarInfo(String JsonCarNum,String JsonCarId, int isEtcNum, String durableYears, MutableLiveData<Result<String>> bindJsonCarLiveData) {
        try {
            JSONObject bindJsonCarInfoJson = new JSONObject();
            bindJsonCarInfoJson.put("plateNumber",JsonCarNum);
            bindJsonCarInfoJson.put("typeId",JsonCarId);
            bindJsonCarInfoJson.put("etcNumHave",isEtcNum);
            bindJsonCarInfoJson.put("inspect",durableYears);
            String jsonParam = bindJsonCarInfoJson.toString();
            RequestBody bindJsonCarBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .bindCarInfo(bindJsonCarBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            bindJsonCarLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        bindJsonCarLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,bindJsonCarLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            bindJsonCarLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            bindJsonCarLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 获取 "车辆信息"页面的数据：包括车型自带的厂商品牌信息，还包括用户手动录入的信息如车牌号等
     * @param JsonCarInfoPageLiveData: 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getMyCarInfo(MutableLiveData<Result<JsonCar>> JsonCarInfoPageLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getMyCarInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            JsonCarInfoPageLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonCar> jsonModel) -> {
                        JsonCarInfoPageLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,JsonCarInfoPageLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            JsonCarInfoPageLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            JsonCarInfoPageLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 退出登录
     * @param logoutLiveData
     */
    public void logout(MutableLiveData<Result<String>> logoutLiveData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .Logout()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            logoutLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        logoutLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,logoutLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            logoutLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            logoutLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 获得订单详情
     *
     * VM层调用M层（Repository+DataSource）
     * @param orderId : 订单ID
     * @param orderDetailLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     * @return
     */
    public void getOrderDetail(String orderId, MutableLiveData<Result<JsonOrderDetailData>> orderDetailLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getOrderDetail(orderId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            orderDetailLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonOrderDetailData> jsonModel) -> {
                        orderDetailLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,orderDetailLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            orderDetailLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            orderDetailLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 获取计划单列表
     * @param pageNum：   页码
     * @param pageSize：  每页显示条目数
     * @return
     */
    public void getPlanOrders(int pageNum, int pageSize, MutableLiveData<Result<JsonOrderListData<OrderItem>>> jsonPlanOrderListLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getPlanOrders(pageNum,pageSize)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                           // jsonPlanOrderListLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonOrderListData<OrderItem>> jsonModel) -> {
                        jsonPlanOrderListLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,jsonPlanOrderListLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            jsonPlanOrderListLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            jsonPlanOrderListLiveData.postValue(Result.error(e.getCause()));
        }
    }


    /**
     * 申请任务
     * @param orderId 订单ID
     * @param applayTaskLiveData： 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void applyTask(String orderId, MutableLiveData<Result<String>> applayTaskLiveData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .applayTask(orderId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            applayTaskLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        applayTaskLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,applayTaskLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            applayTaskLiveData.postValue(Result.error(throwable));
                        }
                    });
        } catch (Exception e) {
            applayTaskLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * step2.调用业务服务器的上传榜单接口，上传图片URL与本次业务的标识如“榜单”，最终完成上传榜单信息等操作
     *
     * @param poundsListInfo:榜单信息
     *
     */
    public void postPoundsListInfo(PoundsListBean poundsListInfo, MutableLiveData<Result<String>> postPoundsLiveData) {

        try {
            String jsonPoundsInfo= new Gson().toJson(poundsListInfo, PoundsListBean.class);
            MyLogCat.i(TAG,"jsonPoundsInfo="+jsonPoundsInfo);
            RequestBody poundsBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonPoundsInfo);
            mSubscription = RetrofitManager.getApiService()
                    .postPoundsList(poundsBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            postPoundsLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        postPoundsLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,postPoundsLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            postPoundsLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            postPoundsLiveData.postValue(Result.error(e.getCause()));
        }
        return;
    }


    /**
     * 获取当前任务的位置轨迹
     * @param taskId: 当前正在进行的运输任务ID
     * @param startTime: 查询的轨迹起始时间
     * @param endTime： 查询的轨迹结束时间
     * @param trackLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getTrack(String taskId, long startTime, long endTime, MutableLiveData<Result<JsonTrackData>> trackLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getTrack(taskId,startTime,endTime)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            trackLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonTrackData> jsonModel) -> {
                      //  testPrint(jsonModel);
                        trackLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,trackLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            trackLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            trackLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 用于测试打印位置轨迹json串
     * @param json
     */
    private void testPrint(JsonDataCommon<JsonTrackData> json) {
        JsonTrackData data = json.getData();
        if(data != null){
            List<LocationPack> locations =  data.getLocations();
            if(locations != null)
            {
                for(LocationPack locationPack:locations){
                    locationPack.setUpTimeStr(locationPack.getUpTime());
                    String locJsonStr = new Gson().toJson(json);
                    MyLogCat.i(TAG,"locJsonStr="+locJsonStr);
                }
            }
        }

    }

    /**
     * 获取当前正在进行的任务
     */
    public void getCurTask(MutableLiveData<Result<TaskItem>> curTaskLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getCurTask()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                          //  curTaskLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<TaskItem> jsonModel) -> {
                        curTaskLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,curTaskLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            curTaskLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            curTaskLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 根据手机号查找用户
     * @param mobileNum
     * @param searchUserLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void searchUserByMobile(String mobileNum, String taskId,MutableLiveData<Result<JsonSearchUserData>> searchUserLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .searchUserByMobile(mobileNum,taskId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            searchUserLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonSearchUserData> jsonModel) -> {
                        searchUserLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,searchUserLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            searchUserLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            searchUserLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 分享或转派任务
     *
     * @param taskId： 要转派（共享）的任务ID
     * @param targetUserId：转派（共享）给的目标用户
     * @param shareOrForward : 1转派； 2共享
     * @param shareForwardLiveData: 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void shareForward(String taskId, String targetUserId, int shareOrForward, MutableLiveData<Result<String>> shareForwardLiveData) {
        try {
            JSONObject shareForwardJson = new JSONObject();
            shareForwardJson.put("id",taskId);
            shareForwardJson.put("type",shareOrForward);
            shareForwardJson.put("userId",targetUserId);
            String jsonParam = shareForwardJson.toString();
            RequestBody shareForwardBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);
            mSubscription = RetrofitManager.getApiService()
                    .shareForward(shareForwardBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            shareForwardLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        shareForwardLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,shareForwardLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            shareForwardLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            shareForwardLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 同意还是拒绝 别人的转派和分享
     * @param taskId : 别人转派（分享）过来的任务ID
     * @param isAgree : 1 同意；0拒绝
     * @param type ： 1转派，2共享
     * @param mark
     * @param shareForwardVerify 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void shareForwardVerify(String taskId, int isAgree, int type, String mark, MutableLiveData<Result<String>> shareForwardVerify) {

        try {
            JSONObject shareForwardSureJson = new JSONObject();
            shareForwardSureJson.put("id",taskId);
            shareForwardSureJson.put("type",type);
            shareForwardSureJson.put("status",isAgree);
            shareForwardSureJson.put("mark",mark);
            String jsonParam = shareForwardSureJson.toString();
            RequestBody shareForwardSureBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);
            mSubscription = RetrofitManager.getApiService()
                    .shareForwardVerify(shareForwardSureBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            shareForwardVerify.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        shareForwardVerify.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,shareForwardVerify);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            shareForwardVerify.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            shareForwardVerify.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 获取未读消息数
     * @param unReadNumLiveData 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getUnReadNum(MutableLiveData<Result<String>> unReadNumLiveData) {

        try {

            mSubscription = RetrofitManager.getApiService()
                    .getUnReadNum()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                         //   unReadNumLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        unReadNumLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,unReadNumLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            unReadNumLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            unReadNumLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 列表项点击后，提交“消息已读”接口
     * @param msgId: 当前消息ID
     * @param isAll: 是否全部清除已读，1全部; 否则 0,只清除当前 msgId为已读
     * @param hasReadLiveData：服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void postHasRead(String msgId, int isAll, MutableLiveData<Result<String>> hasReadLiveData) {
        try {
            JSONObject hasReadJson = new JSONObject();
            hasReadJson.put("id",msgId);
            hasReadJson.put("isAll",isAll);
            String jsonParam = hasReadJson.toString();
            RequestBody hasReadBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonParam);

            mSubscription = RetrofitManager.getApiService()
                    .postHasRead(hasReadBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            //unReadNumLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        hasReadLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,hasReadLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            hasReadLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            hasReadLiveData.postValue(Result.error(e.getCause()));
        }
    }


    /**
     * @param pageNum: 分页页码
     * @param pageSize：每页显示的条目数
     * @param msgType： 消息类别
     * @param msgListLiveData: 服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getMsgList(int pageNum, int pageSize, String msgType, MutableLiveData<Result<JsonMsgListData>> msgListLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .getMsgList(pageNum,pageSize,msgType)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            //   unReadNumLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonMsgListData> jsonModel) -> {
                        msgListLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,msgListLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            msgListLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            msgListLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 检查磅单状态
     * @param taskId:任务ID
     * @param checkPoundsStateLiveData  服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void checkPoundsState(String taskId, MutableLiveData<Result<JsonPoundsState>> checkPoundsStateLiveData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .checkPoundsState(taskId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                               checkPoundsStateLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonPoundsState> jsonModel) -> {
                        checkPoundsStateLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,checkPoundsStateLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            checkPoundsStateLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            checkPoundsStateLiveData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 撤销任务
     * @param taskId：要撤销的任务ID
     * @param cancelTaskLiveData
     */
    public void cancelTask(String taskId, MutableLiveData<Result<String>> cancelTaskLiveData) {

        try {
            mSubscription = RetrofitManager.getApiService()
                    .cancelTask(taskId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            cancelTaskLiveData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<String> jsonModel) -> {
                        cancelTaskLiveData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,cancelTaskLiveData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            cancelTaskLiveData.postValue(Result.error(throwable));
                        }
                    });
            return;

        } catch (Exception e) {
            cancelTaskLiveData.postValue(Result.error(e.getCause()));
        }
    }
    /**
     * 获取某一天的统计数据
     * @param date： 某一天的日期
     * @param statisticData：统计数据，服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getStatisticOneDay(String date, MutableLiveData<Result<JsonStatisticsOneDayData>> statisticData) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .getStatisticsOneDay(date)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            statisticData.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonStatisticsOneDayData> jsonModel) -> {
                        statisticData.postValue(Result.response(jsonModel));
                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,statisticData);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            statisticData.postValue(Result.error(throwable));
                        }
                    });
            return;
        } catch (Exception e) {
            statisticData.postValue(Result.error(e.getCause()));
        }
    }

    /**
     * 按照 年，月，周统计数据
     * @param type ：  0代表周;  1代表月;  2代表年
     * @param year ：       type为1或2时传递
     * @param month :      type为1时传递
     * @param startTime : type为0时，传递周的开始时间
     * @param endTime :    type为0时，传递周的结束时间
     * @param statisticYmd  统计数据，服务器返回的数据 将填充进LiveData,以便通知UI层
     */
    public void getStatisticByYmd(int type, int year, int month,
                                  long startTime, long endTime,
                                  MutableLiveData<Result<JsonStatisticsYmdData>> statisticYmd) {
        try {
            mSubscription = RetrofitManager.getApiService()
                    .getStatisticsYmdData(type,year,month,startTime,endTime)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            //statisticYmd.postValue(Result.loading(""));
                        }
                    })
                    //接口返回的code值与Http Code的值都返回200时表示成功（业务成功）
                    .subscribe((JsonDataCommon<JsonStatisticsYmdData> jsonModel) -> {
                        jsonModel.getData().setMonth(month);
                        statisticYmd.postValue(Result.response(jsonModel));

                    }, (Throwable throwable) -> {
                        //接口code（HttpCode）值不是200时，表示业务失败或者HTTP失败，在下面要区分是业务失败还是HTTP失败
                        if (throwable instanceof HttpException) {
                            String exceptionMsg = dealExceptionContent(throwable,statisticYmd);
                            MyLogCat.i(TAG,"exceptionMsg="+exceptionMsg);
                        }
                        else {
                            statisticYmd.postValue(Result.error(throwable));
                        }
                    });
            return;
        } catch (Exception e) {
            statisticYmd.postValue(Result.error(e.getCause()));
        }
    }
}